import { Evaluator } from "rollup-web";
import * as Mocha from "@forsee/mocha";
import { wrap } from "comlink";
const useTest = (Eval: Evaluator, port: MessagePort, testURL: string) => {
    const judge = new Mocha.Judge();
    const api = wrap(port);
    return {
        setup() {
            return judge.setupBDD((context) => {
                return Eval.evaluate(testURL);
            });
        },
        run() {
            judge.run((i) => {
                api.onEnd();
                console.log(i, "测试完成啦");
            });
            judge.reporter.addReceiver((event) => {
                const a = [...event];
                a[1].file && (a[1].file = a[1].file.toString());

                api.onChange(a);
            });
        },
    };
};
globalThis.__Mocha__ = Mocha;
const Eval = new Evaluator();
globalThis.__Rollup_Env__ = Eval;
/* 初始化 Compiler 线程的端口, 需要接收到实体的 port，故而需要进行信息接收 */
const EvalInit = async (e) => {
    if (e.data && e.data.password === "__rollup_init__" && e.data.port) {
        await Eval.useWorker(e.data.port);
        await Eval.createEnv({
            worker: "module",
            env: "worker_module",
            root: e.data.localURL,
        });
        removeEventListener("message", EvalInit);
        let runTest = () => {
            console.warn("此次没有发现测试代码");
        };
        postMessage("__rollup_init__");
        if (e.data.testPort && e.data.testUrl) {
            const { setup, run } = useTest(
                Eval,
                e.data.testPort,
                e.data.testUrl
            );
            runTest = run;
            await setup();
        }

        console.log("Worker 初始化完成", e.data.localURL);
        await Eval.evaluate(e.data.localURL);
        runTest();
    }
};
addEventListener("message", EvalInit);

addEventListener("beforeunload", () => {
    Eval.destroy();
});
postMessage("__rollup_ready__");
